package com.example.compreshensiveshop.service.imp;

import com.example.compreshensiveshop.dao.ProductDao;
import com.example.compreshensiveshop.dto.*;
import com.example.compreshensiveshop.po.ProductImagePO;
import com.example.compreshensiveshop.po.ProductPO;
import com.example.compreshensiveshop.service.CategoryService;
import com.example.compreshensiveshop.service.ProductImageService;
import com.example.compreshensiveshop.service.ProductService;
import com.example.compreshensiveshop.service.SkuService;
import com.example.compreshensiveshop.vo.PageResultVO;
import com.example.compreshensiveshop.vo.ProductImagesVO;
import com.example.compreshensiveshop.vo.ProductMessageVO;
import com.example.compreshensiveshop.vo.ProductVO;
import com.example.compreshensiveshop.vo.SkuListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Product Service Implementation
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private SkuService skuService;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private CategoryService categoryService;
    @Override
    public PageResultVO<ProductVO> queryProductsByCondition(ProductQueryDTO queryDTO) {
        // 计算偏移量
        Integer offset = (queryDTO.getPage() - 1) * queryDTO.getSize();

        // 调试日志
        System.out.println("查询参数 - categoryId: " + queryDTO.getCategoryId()
                + ", keyword: " + queryDTO.getKeyword()
                + ", sellerId: " + queryDTO.getSellerId()
                + ", status: " + queryDTO.getStatus()
                + ", page: " + queryDTO.getPage()
                + ", size: " + queryDTO.getSize()
                + ", offset: " + offset);

        // 查询数据列表
        List<ProductVO> productList = productDao.queryProductsByCondition(
                queryDTO.getCategoryId(),
                queryDTO.getKeyword(),
                queryDTO.getSellerId(),
                queryDTO.getStatus(),
                offset,
                queryDTO.getSize()
        );

        // 查询总记录数
        Long total = productDao.countProductsByCondition(
                queryDTO.getCategoryId(),
                queryDTO.getKeyword(),
                queryDTO.getSellerId(),
                queryDTO.getStatus()
        );

        // 调试日志
        System.out.println("查询结果 - 数据条数: " + productList.size() + ", 总记录数: " + total);

        // 计算总页数
        Integer pages = (int) Math.ceil((double) total / queryDTO.getSize());

        // 构建分页结果
        PageResultVO<ProductVO> pageResult = new PageResultVO<>();
        pageResult.setList(productList);
        pageResult.setTotal(total);
        pageResult.setPage(queryDTO.getPage());
        pageResult.setSize(queryDTO.getSize());
        pageResult.setPages(pages);

        return pageResult;
    }

    @Override
    public Long addProduct(ProductCreateDTO productCreateDTO) {
        ProductPO productPO = ProductPO.builder()
                .categoryId(productCreateDTO.getCategoryId())
                .name(productCreateDTO.getProductName())
                .price(productCreateDTO.getProductPrice())
                .description(productCreateDTO.getProductDescription())
                .image(productCreateDTO.getProductImage())
                .sellerId(productCreateDTO.getSellerId())
                .build();
        productDao.addProduct(productPO);
        List<ProductImagePO> productImagePOS = new ArrayList<>();
        for(ProductImagesCreateDTO productImagesCreateDTO : productCreateDTO.getProductImages()){
            ProductImagePO productImagePO = ProductImagePO.builder()
                    .productId(productPO.getId())
                    .url(productImagesCreateDTO.getUrl())
                    .build();
            productImagePOS.add(productImagePO);
        }
        productImageService.addProductImages(productImagePOS);
        return productPO.getId();
    }

    @Override
    public void updateProduct(ProductUpdateDTO productUpdateDTO) {
        ProductPO productPO = ProductPO.builder()
                .id(productUpdateDTO.getProductId())
                .categoryId(productUpdateDTO.getCategoryId())
                .name(productUpdateDTO.getProductName())
                .price(productUpdateDTO.getProductPrice())
                .description(productUpdateDTO.getProductDescription())
                .image(productUpdateDTO.getProductImage())
                .status(productUpdateDTO.getStatus())
                .stock(productUpdateDTO.getStock())
                .build() ;
        productDao.updateMessageById(productPO);
        List<ProductImagePO> productImagePOS = new ArrayList<>();
        List<ProductImagePO> productImageInsertPOS = new ArrayList<>();
        for(ProductImagesUpdateDTO productImagesUpdateDTO : productUpdateDTO.getProductImages()){
            ProductImagePO productImagePO = ProductImagePO.builder()
                    .id(productImagesUpdateDTO.getId())
                    .productId(productPO.getId())
                    .url(productImagesUpdateDTO.getUrl())
                    .build();
            if(productImagesUpdateDTO.getId()==null){
                productImageInsertPOS.add(productImagePO);
            }else{
                productImagePOS.add(productImagePO);
            }

        }
        for (ProductImagePO productImagePO : productImagePOS){
            productImageService.updateProductImages(productImagePO);
        }
        if(!productImageInsertPOS.isEmpty()){ productImageService.addProductImages(productImageInsertPOS);}

    }

    @Override
    public void updateStatus(Long id, Integer status) {
         productDao.updateStatus(id,status);
    }

    @Override
    public void deleteImages(Long id) {
        productImageService.deleteImages(id);
    }

    @Override
    public List<ProductPO> getProductByKeyword(String keyword) {
        return productDao.getProductByKeyword(keyword);
    }

    @Override
    public List<ProductPO> getProductByCategory(String category) {
        return productDao.getProductByCategory(category);
    }


    @Override
    public void addProductSku(SkuCreateDTO skuCreateDTO) {
         skuService.addProductSku(skuCreateDTO);
        ProductPO productPO = productDao.queryMessageById(skuCreateDTO.getProductId());
        BigDecimal tempPrice = BigDecimal.valueOf(0);
        if(productPO.getPrice().compareTo(tempPrice)==0){
            productPO.setPrice(skuCreateDTO.getPrice());
        }
        if(skuCreateDTO.getPrice().compareTo(productPO.getPrice())<0){
            productPO.setPrice(skuCreateDTO.getPrice());
        }
        Integer stock = skuService.queryStock(skuCreateDTO.getProductId());
        if(stock==null){
            stock = 0;
        }
        productPO.setStock(stock);
        productDao.updateMessageById(productPO);
    }

    @Override
    public List<SkuListVO> queryByPId(Long productId) {
        return skuService.queryByPId(productId);
    }

    @Override
    public void updateProductSku(SkuUpdateDTO skuUpdateDTO) {
        skuService.updateProductSku(skuUpdateDTO);

    }

    @Override
    public void lockStock(Long skuId, Integer quantity) {
        skuService.lockStock(skuId,quantity);
    }

    @Override
    public void backStock(Long skuId, Integer quantity) {
        skuService.backStock(skuId,quantity);
    }

    @Override
    public void releaseStock(Long skuId, Integer quantity) {
        productDao.updateStockAndSales(skuId,quantity);
      skuService.releaseStock(skuId,quantity);
    }

    @Override
    public ProductMessageVO queryMessageById(Long id) {
        List<ProductImagesVO> productImages = productImageService.queryByPId(id);
        ProductMessageVO productMessageVO = productDao.queryProductMessageById(id);
        productMessageVO.setProductImages(productImages);
        String categoryName = categoryService.queryCategoryNameById(id);
        productMessageVO.setCategoryName(categoryName);
        return productMessageVO;
    }

    @Override
    public String queryProductMainImage(Long skuId) {
        return productDao.queryProductMainImage(skuId);
    }

    @Override
    public String queryProductSkuName(Long skuId) {
        return skuService.queryProductSkuName(skuId);
    }
    
    @Override
    public void incrementViewCount(Long productId) {
        productDao.incrementViewCount(productId);
    }
}